import React, { useEffect, useState } from 'react'
import Layout from './Layout'
import { Button, Col, Empty, Row, Space } from 'antd'
import CheckBox from './CheckBox'
import RadioBox from './RadioBox'
import { useDispatch } from 'react-redux'
import { filterProduct } from '../../store/actions/product.action'
import { useSelector } from '../../hooks/useSelector'
import ProductItem from './ProductItem'
const Shop = () => {
  const dispatch = useDispatch()
  const [skip,setSkip] = useState<number>(0)
  const product = useSelector(state=>state.product)
  const [ myFilters, setMyFilters ] = useState<{category: string[],price:number[]}>({category: [], price: []})
  
  useEffect(()=> {
    setSkip(0)
  },[myFilters])

  useEffect(()=>{
    dispatch(filterProduct({filters: myFilters,skip}))
  },[myFilters,skip])

  const filterDOM = ()=>(
    <Space size={'middle'} direction="vertical">
      <CheckBox hanleFilter={(filters:string[])=>{
        setMyFilters({...myFilters, category: filters})
      }}/>
      <RadioBox hanleFilter={(filters:number[])=>{
        setMyFilters({...myFilters, price: filters})
      }} />
    </Space>
  )

  const productDOM = () => (
    <Row gutter={[16,16]}>
      {product.filter.result.data.map(item=>(
        <Col span={6} key={ item._id }>
        <ProductItem  product={item}/>
      </Col>
      ))}
    </Row>
  )
  
  const loadMoreButton = () => {
    return (
      <Row>
        {product.filter.result.size>=4&& <Button onClick={loadMore}>加载更多</Button>}
      </Row>
    )
  }

  const loadMore = ()=> {
    setSkip(skip+4)
  }

  const noData = ()=>{
    return <Row>
      {product.filter.result.size<4&&<Empty/>}
    </Row>
  }

  return (
    <Layout title='商城' subTitle='挑选你喜欢的商品吧'>
      <Row>
        <Col span={4}>
          {filterDOM()}
        </Col>
        <Col span={20}>
          {productDOM()}{loadMoreButton()}{noData()}
        </Col>
      </Row>
    </Layout>
  )
}

export default Shop